package cn.lanqiao.book.controller;

import cn.lanqiao.book.dao.IBookDao;
import cn.lanqiao.book.dao.ICategoryDao;
import cn.lanqiao.book.dao.IChapterDao;
import cn.lanqiao.book.dao.impl.BookDaoImplI;
import cn.lanqiao.book.dao.impl.CategoryDaoImplI;
import cn.lanqiao.book.dao.impl.ChapterDaoImplI;
import cn.lanqiao.book.pojo.Book;
import cn.lanqiao.book.pojo.category;
import cn.lanqiao.book.pojo.chapter;
import cn.lanqiao.book.service.impl.BookShelfServiceImpl;
import com.alibaba.fastjson.JSON;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BookServlet extends HttpServlet {
    Book bo = new Book();
    IBookDao bd = new BookDaoImplI();
    IChapterDao chd = new ChapterDaoImplI();
    chapter ch = new chapter();
    ICategoryDao cd = new CategoryDaoImplI();
    category c = new category();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("_method");
        try {
            Method m = getClass().getMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            m.invoke(this, req, resp);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public void addBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("1");
        HttpSession session = req.getSession();
        resp.setContentType("text/html; charset=UTF-8");
        PrintWriter out = resp.getWriter();
        Object type = session.getAttribute("type");

        if (type == null) {
            req.getRequestDispatcher("/invalidateLogin.jsp").forward(req, resp);
        } else {
            System.out.println("2");
            int type1 = (int) type;
            if (type1 == 3 || type1 == 2) {
                String name = req.getParameter("b_name");
                System.out.println(name);
                String author = req.getParameter("b_author");
                System.out.println(author);
                String description = req.getParameter("b_description");
                System.out.println(description);
                String image = "".equals(req.getParameter("b_image"))||null==req.getParameter("b_image")?"default_cover.png":req.getParameter("b_image");
                System.out.println(image);
                int cid = Integer.parseInt(req.getParameter("c_id"));
                System.out.println(cid);
//                shangchuan(req,resp);
                bo.setB_name(name);
                bo.setB_author(author);
                bo.setB_description(description);
                bo.setB_image(image);
                bo.setC_id(cid);
                bd.addBook(bo);
            }
        }
        req.getRequestDispatcher("/mutilBook?_method=selectBook").forward(req, resp);
    }

    public void deleteBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        resp.setContentType("text/html; charset=UTF-8");
        PrintWriter out = resp.getWriter();
        Object type = session.getAttribute("type");
        if (type == null) {
            req.getRequestDispatcher("/invalidateLogin.jsp").forward(req, resp);
        } else {
            int type1 = (int) type;
            if (type1 == 3 || type1 == 2) {
                String name = req.getParameter("b_name");
                bo = bd.queryForOne(name);
                int id = bo.getB_id();
                chd.deleteChaptervyid(id);
                bd.deleteBook(name);


            } else {
                req.getRequestDispatcher("/invalidateLogin.jsp").forward(req, resp);
            }
            req.getRequestDispatcher("/book.jsp").forward(req, resp);
        }
    }
    public void deleteBook1(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        resp.setContentType("text/html; charset=UTF-8");
        PrintWriter out = resp.getWriter();
        Object type = session.getAttribute("type");
        if (type == null) {
            req.getRequestDispatcher("/invalidateLogin.jsp").forward(req, resp);
        } else {
            int type1 = (int) type;
            if (type1 == 3 || type1 == 2) {
                String name = req.getParameter("b_name");
                bo = bd.queryForOne(name);
                int id = bo.getB_id();
                chd.deleteChaptervyid(id);
                bd.deleteBook(name);
            } else {
                req.getRequestDispatcher("/invalidateLogin.jsp").forward(req, resp);
            }
        }
    }

    public void selectBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        resp.setContentType("text/html; charset=UTF-8");
        PrintWriter out = resp.getWriter();
        Object type = session.getAttribute("type");

        if (type == null) {
            req.getRequestDispatcher("/invalidateLogin.jsp").forward(req, resp);
        } else {
            int type1 = (int) type;
            if (type1 == 2 || type1 == 3) {
                List<Book> l = new ArrayList<>();
                l = bd.queryAll();
                int cid;
                String name;
                Map<Book, String> categorymap = new HashMap<>();
                for (Book book : l) {
                    cid = book.getC_id();
                    c = cd.queryForOnebyid(cid);
                    name = c.getC_name();
                    categorymap.put(book, name);
                }
                req.setAttribute("book", l);
                req.setAttribute("categorymap", categorymap);
                req.getRequestDispatcher("/book.jsp").forward(req, resp);
            } else {
                req.getRequestDispatcher("/invalidateLogin.jsp").forward(req, resp);
            }
        }
    }

    public void qurryBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html; charset=UTF-8");
        PrintWriter out = resp.getWriter();
        HttpSession session = req.getSession();
        Object type = session.getAttribute("type");
        if (type == null) {
            req.getRequestDispatcher("/invalidateLogin.jsp").forward(req, resp);
        } else {
            int type1 = (int) type;
            if (type1 == 3 || type1 == 2) {
                String name = req.getParameter("b_name");
                bo = bd.queryForOne(name);
                req.setAttribute("book", bo);
                req.getRequestDispatcher("/updatebook.jsp").forward(req, resp);
            } else {
                req.getRequestDispatcher("/invalidateLogin.jsp").forward(req, resp);
            }
        }
    }

    public void updateBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("b_name");
        String author = req.getParameter("b_author");
        String description = req.getParameter("b_description");
        String image = req.getParameter("b_image");
        int cid = Integer.parseInt(req.getParameter("c_id"));
        int bid = Integer.parseInt(req.getParameter("b_id"));




        bo.setB_name(name);
        bo.setB_author(author);
        bo.setB_description(description);
        bo.setB_image(image);
        bo.setC_id(cid);
        bo.setB_id(bid);
        bd.updateBook(bo);
        req.getRequestDispatcher("/mutilBook?_method=selectBook").forward(req, resp);
    }

    public void searchBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html; charset=UTF-8");
        PrintWriter out = resp.getWriter();
        String name = req.getParameter("b_name");
        name = "%" + name + "%";
        List<Book> l = new ArrayList<>();
        l = bd.search(name);
        int cid;
        String name1;
        Map<Book, String> categorymap = new HashMap<>();
        for (Book book : l) {
            cid = book.getC_id();
            c = cd.queryForOnebyid(cid);
            name1 = c.getC_name();
            categorymap.put(book, name1);
        }
        req.setAttribute("book", l);
        req.setAttribute("categorymap", categorymap);
        req.setAttribute("book", l);
        req.getRequestDispatcher("/book.jsp").forward(req, resp);
    }

    public void Bookcontent(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html; charset=UTF-8");
        PrintWriter out = resp.getWriter();
        HttpSession session = req.getSession();
        String name = req.getParameter("b_name2");
        int chid = Integer.parseInt(req.getParameter("ch_id1"));
        bo = bd.queryForOne(name);
        int id = bo.getB_id();
        ch = chd.queryForOnebychid(chid);
        String chname = ch.getCh_name();
        String con = ch.getCh_content();
        con = con.replaceAll("\\r\\n","<br>");
        int bid = bo.getB_id();
        c = cd.queryForOnebyid(bo.getC_id());
        String cname = c.getC_name();
        req.setAttribute("con", con);
        req.setAttribute("cname", cname);
        req.setAttribute("book", bo);
        req.setAttribute("chname", chname);
        req.setAttribute("chid", chid);
        //将本书本章节阅读记录保存到临时书架
        saveChapter(bid,chid,session);

        bd.watchcount(bid);



        req.getRequestDispatcher("/fiction.jsp").forward(req, resp);

    }

    public void shangBookcontent(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html; charset=UTF-8");
        PrintWriter out = resp.getWriter();
        HttpSession session = req.getSession();
        String name = req.getParameter("b_name2");
        int chid = Integer.parseInt(req.getParameter("ch_id1"));
        bo = bd.queryForOne(name);
        int id = bo.getB_id();
        ch = chd.shang(chid, id);
        if (ch == null) {

//            ch = chd.queryForOnebychid(chid);
//            String chname = ch.getCh_name();
//            String con = ch.getCh_content();
//            con = con.replaceAll("\\r\\n","<br>");
//            int bid = bo.getB_id();
//            c = cd.queryForOnebyid(bo.getC_id());
//            String cname = c.getC_name();
//
//            req.setAttribute("con", con);
//            req.setAttribute("cname", cname);
//            req.setAttribute("book", bo);
//            req.setAttribute("chname", chname);
//            req.setAttribute("chid", chid);
//            req.getRequestDispatcher("/fiction.jsp").forward(req, resp);

            resp.getWriter().write("当前为第一章");


        } else {
            resp.setContentType("application/json;charset=utf-8");
            String chname = ch.getCh_name();
            String con = ch.getCh_content();
            int bid = bo.getB_id();
            c = cd.queryForOnebyid(bo.getC_id());
            String cname = c.getC_name();

            chid = ch.getCh_id();
            //将本书本章节阅读记录保存到临时书架
            saveChapter(bid,chid,session);
            req.setAttribute("con", con);
            req.setAttribute("cname", cname);
            req.setAttribute("book", bo);
            req.setAttribute("chname", chname);
            req.setAttribute("chid", chid);

            Map<String ,Object > m = new HashMap<>();
            m.put("bname",bo.getB_name());
            m.put("chid",chid);
            resp.getWriter().write(JSON.toJSONString(m));

        }
    }



    public void xiaBookcontent(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html; charset=UTF-8");
        PrintWriter out = resp.getWriter();
        HttpSession session = req.getSession();
        String name = req.getParameter("b_name2");
        int chid = Integer.parseInt(req.getParameter("ch_id1"));
        bo = bd.queryForOne(name);
        int id = bo.getB_id();
        ch = chd.xia(chid, id);
        if (ch == null) {
//            ch = chd.queryForOnebychid(chid);
//            String chname = ch.getCh_name();
//            String con = ch.getCh_content();
//            int bid = bo.getB_id();
//            c = cd.queryForOnebyid(bo.getC_id());
//            String cname = c.getC_name();
//            con = con.replaceAll("\\r\\n","<br>");
//            req.setAttribute("con", con);
//            req.setAttribute("cname", cname);
//            req.setAttribute("book", bo);
//            req.setAttribute("chname", chname);
//            req.setAttribute("chid", chid);
//            req.setAttribute("page",1);
//            req.getRequestDispatcher("/fiction.jsp").forward(req, resp);
            resp.getWriter().write("当前为最后一章");

        } else {
            resp.setContentType("application/json;charset=utf-8");
            String chname = ch.getCh_name();
            String con = ch.getCh_content();
            int bid = bo.getB_id();
            c = cd.queryForOnebyid(bo.getC_id());
            String cname = c.getC_name();

            chid = ch.getCh_id();
            //将本书本章节阅读记录保存到临时书架
            saveChapter(bid,chid,session);
            req.setAttribute("con", con);
            req.setAttribute("cname", cname);
            req.setAttribute("book", bo);
            req.setAttribute("chname", chname);
            req.setAttribute("chid", chid);
            req.setAttribute("page",2);

            Map<String ,Object > m = new HashMap<>();
            m.put("bname",bo.getB_name());
            m.put("chid",chid);
            resp.getWriter().write(JSON.toJSONString(m));
        }

    }

    public void topBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html; charset=UTF-8");
        PrintWriter out = resp.getWriter();

        List<Book> lb = new ArrayList<>();
        lb = bd.topBook();
        Map<Book, String> categorymap = new HashMap<>();
        Map<Book, String> chaptermap = new HashMap<>();
        Map<Book, String> stamap = new HashMap<>();
        Map<Book, Integer> chidmap = new HashMap<>();
        int cid;
        int bid;
        String cname;
        String chname;
        String sta;
        int chid;
        for (Book book : lb) {
            cid = book.getC_id();
            bid = book.getB_id();
            cname = cd.queryForOnebyid(cid).getC_name();

            categorymap.put(book, cname);
            chname = chd.queryForOnebyid(bid)==null?"":chd.queryForOnebyid(bid).getCh_name();
            chid =  chd.queryForOnebyid(bid)==null?-1:chd.queryForOnebyid(bid).getCh_id();
            chidmap.put(book, chid);
            chaptermap.put(book, chname);
            if (book.getB_state() == 1) {
                sta = "连载中";
            } else {
                sta = "已完结";
            }
            stamap.put(book, sta);

        }
        req.setAttribute("book", lb);
        req.setAttribute("categorymap", categorymap);
        req.setAttribute("chaptermap", chaptermap);
        req.setAttribute("stamap", stamap);
        req.setAttribute("chid", chidmap);
        req.getRequestDispatcher("/rankinglist.jsp").forward(req, resp);
    }
    public void saveChapter(int book_id,int chapter_id,HttpSession session){
        //获取当前用户名
        String u_username= (String) session.getAttribute("username");
        //如果用户未登录
        if(u_username==null){
            return;
        }
        BookShelfServiceImpl.getInstance().addBookToShelf(book_id,chapter_id,u_username);
    }


    protected void shangchuan(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1 判断请求是文件上传还是普通表单提交
        if(ServletFileUpload.isMultipartContent(req)){
            // 2  创建FileItemFactory
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            //3 创建用户解析上传数据的工具类ServletFileUpload
            ServletFileUpload fileUpload = new ServletFileUpload(fileItemFactory);
            // 4 解析上传数据
            try {
                List<FileItem> list =    fileUpload.parseRequest(req);
                //循环判断  每一个表单项 是普通类型还是上传数据
                for(FileItem item : list){
                    //判断每一个具体的表单项
                    if(item.isFormField()){//判断是普通的表单项
                        // UTF-8 可以解决中文乱码
                    }else{//上传文件
                        // 实现文件上传
                        item.write(new File("D://workspace//book_website//src//main//webapp//images//" + item.getName()));
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    public void likecount(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html; charset=UTF-8");
        PrintWriter out = resp.getWriter();
        HttpSession session = req.getSession();
        int bid = Integer.parseInt(req.getParameter("b_id"));

        bd.likecount(bid);

        resp.getWriter().write("投票成功");
    }
    public void checkBid(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html; charset=UTF-8");
        PrintWriter out = resp.getWriter();
        HttpSession session = req.getSession();
        int bid;
        bid = Integer.parseInt(req.getParameter("b_id"));
        Book book = bd.queryForOnebybid(bid);
        int flag=1;

        if (null == book){
            //无此书，不可添加
            flag = 2;
            resp.getWriter().write(""+flag);
        }else{
            //有此书，可以添加
            resp.getWriter().write(""+flag);
        }
    }
    public void checkbidchid(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html; charset=UTF-8");
        PrintWriter out = resp.getWriter();
        HttpSession session = req.getSession();
        int bid;
        int chid;
        bid = Integer.parseInt(req.getParameter("b_id"));
        chid = Integer.parseInt(req.getParameter("ch_id"));
        chapter chapter = chd.querybybidchid(bid,chid);
        int flag = 1;
        if (null == chapter){
            //无此章节，不可添加
            flag =2;
            resp.getWriter().write(""+flag);
        }else{
            //有此章节，可以添加
            resp.getWriter().write(""+flag);
        }
    }
    public void checkbidchname(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html; charset=UTF-8");
        PrintWriter out = resp.getWriter();
        HttpSession session = req.getSession();
        int bid;
        String chname;
        bid = Integer.parseInt(req.getParameter("b_id"));
        chname=req.getParameter("ch_name");
        chapter chapter = chd.queryForOnebyname(bid,chname);
        int flag = 1;
        if (null == chapter){
            //无此章节，不可添加
            flag =2;
            resp.getWriter().write(""+flag);
        }else{
            //有此章节，可以添加
            resp.getWriter().write(""+flag);
        }
    }
}
